const mime = require('mime');
const path = require("path");

/**
 *  这个express中间件负责提高产出文件的预览
 *  1.拦截HTTP请求，看看请求的文件是不是webpack打包出来的文件
 *  2. 如果是的话，从硬盘上读取出来，返回给客户端
 * @param {*} param0 
 * @returns 
 */
function wrapper(context) {
    return (req,res,next)=>{
        // http://localhost:9000/main.js
        let url = req.url;  // /main.js
        if (url === "/") { url = "/index.html"; }
        //outputPath = path.resolve(__dirname,'dist')
        let filename = path.join(context.outputPath, url); // /Users/adminx/Desktop/Ikki-study/webpack-advanced/webpack5-base/14.hmr/9000/dist/main.js
        try {
            let stat = context.fs.statSync(filename); //读取文件内容
            if (stat.isFile()) {
                let content = context.fs.readFileSync(filename);
                
                res.setHeader("Content-Type", mime.getType(filename));
                res.send(content);
            } else {
                res.sendStatus(404);
            }
        } catch (error) {
            // res.sendStatus(404);
            return next(error)
        }
    }
}
module.exports = wrapper